package com.foreveross.taskservice.engine.worker;

import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.dayatang.utils.DateUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.foreveross.taskservice.common.CacheDataSpace;
import com.foreveross.taskservice.common.TaskStatusEnum;
import com.foreveross.taskservice.common.model.AbstractTaskModel;
import com.foreveross.taskservice.common.model.TaskAction;
import com.foreveross.taskservice.core.domain.channel.GradChannelEntity;
import com.foreveross.taskservice.infra.cfg.PropertyUtils;
import com.foreveross.taskservice.infra.cfg.taskservice.TaskServicePropertiesLoader;
import com.foreveross.taskservice.infra.util.DateUtil;
import com.google.common.collect.Sets;
/**
 * 任务补偿，将失败的任务重新加载到等待队列
 * @author Administrator
 *
 */
public class TaskTimeoutWorker extends AbstractTaskStatefulJobWorker{

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		long stime = System.currentTimeMillis();
		log.info("任务超时检查TaskTimeoutWorker开始........");
		CacheDataSpace space=CacheDataSpace.AirFreightSpace();
		
		List<GradChannelEntity> channels = null;
		LinkedHashSet<AbstractTaskModel> tasks = null;
		LinkedHashSet<AbstractTaskModel> timeoutTasks = Sets.newLinkedHashSet();
		int timeout=PropertyUtils.getIntProperty(
				TaskServicePropertiesLoader.TASKSERVICE_TASK_TIMEOUT, TaskServicePropertiesLoader.FILE_NAME, 3600000);
		if(timeout <= 0) return;//统一控制，如果为０时，不超时
		try {
			channels=getGradChannelApplication().getEnableChannel();
			for(GradChannelEntity e : channels){
				if(e.getTaskTimeout() <= 0) continue;//如果为０时，不超时
				tasks = Sets.newLinkedHashSet(getTaskCacheQuery().queryTaskDetailInfo(space, e.getId(), TaskStatusEnum.TASK_DOING, 0, 50000));
				log.info(e.getName()+"获得的超时正在执行中任务数:" + tasks.size());
				for(AbstractTaskModel t : tasks){
					if(t.getStartTime() != null && new Date().after(DateUtil.addTime(t.getStartTime(), e.getTaskTimeout()))){
						t.setStatus(TaskStatusEnum.TASK_OTHER_FAIL.getStatus());
						t.addAction(new TaskAction(TaskAction.TASK_TIMEOUT, System.currentTimeMillis(), "任务执行超时重置"));
						
						timeoutTasks.add(t);
					}
				}
				log.info(e.getName()+"获得的超时任务数:" + timeoutTasks.size());
				super.getTaskCacheStorage().rollbacks(timeoutTasks);
			}
			
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}finally{
			channels=null;
			tasks = null;
			log.info("任务超时检查TaskTimeoutWorker结束....耗时ms:"+(System.currentTimeMillis()-stime));
		}
	}
	
	public static void main(String[] arg){
		System.out.println(new Date().after(DateUtil.addTime(
				DateUtils.parseDateTime("2014-09-02 20:00:00"), 3600000)));
		System.out.println(DateUtils.isDateAfter(new Date(), DateUtil.addTime(
				DateUtils.parseDateTime("2014-09-02 20:00:00"), 3600000)));
	}

}
